<template>
  <div class="login-view clearfix">
    <div class="login-left fl">
      <div class="login-logo">
        <p class="logo-title">容联<span class="circle"></span>七陌</p>
      </div>
    </div>
    <div class="login-right fl">
      <!--<I18nSelect class="lang-select"></I18nSelect>-->
      <div class="login-box">
        <p class="login-title">登录容联·七陌</p>
        <el-form class="m7-form" ref="loginForm" :model="form" :rules="rules" label-width="0px">
          <el-form-item label="" prop="loginName">
            <el-input
              v-model.trim="form.loginName"
              @keyup.enter.native="loginSubmit"
              placeholder="请输入账号"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="" prop="password">
            <el-input
              v-model.trim="form.password"
              type="password"
              @keyup.enter.native="loginSubmit"
              autocomplete="off"
              placeholder="请输入密码"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="status-box">
          <el-checkbox v-model="form.remember">记住密码</el-checkbox>
          <span @click.stop="showDropdown" class="status-config">状态设置</span>
          <LoginDropdown
            ref="loginDropdownRef"
            @changeWebchatLoginStatus="changeWebchatLoginStatus"
            @change-login-status="changeLoginStatus"
            @change-login-type="changeLoginType"
          >
          </LoginDropdown>
        </div>
        <div class="submit" :class="loginLoading?'loading-circle-wrap':''" @click.stop="loginSubmit">
          <span>{{loginLoading?'登录中':'登录'}}</span>
          <span class="loading-circle">
              <i></i>
              <i></i>
              <i></i>
            </span>
        </div>
        <el-checkbox
          v-model="form.policy"
          v-if="
            getPlatformConfig &&
            getPlatformConfig.m7ServiceTerms &&
            getPlatformConfig.m7PrivacyPolicy
          "
          class="policy-checkbox-wrap"
        >
          <span>
            我已阅读并同意
            <a :href="getPlatformConfig.m7ServiceTerms" target="_blank"
              >《服务协议》</a
            >和<a :href="getPlatformConfig.m7PrivacyPolicy" target="_blank"
              >《隐私政策》</a
            >
          </span>
        </el-checkbox>
      </div>
      <div class="login-footer">
        <!-- <p class="serve-number">客服服务热线：4008-113-114 / 010-80455555</p> -->
        <p class="serve-number">客服服务热线：4001-113-114</p>
        <p>技术支持邮箱：service@7moor.com</p>
        <div class="line"></div>
        <div class="record-number">
          增值电信业务经营许可证B2-20213887<span class="footer-circle">·</span
          >©<span>{{ currentYear }}</span
          >容联七陌<span class="footer-circle">·</span>京ICP备140006443号-1
        </div>
      </div>
    </div>
    <!--绑定手机号-->
    <BindPhone
      @bindPhoneSuccess="bindPhoneSuccess"
      ref="bindPhoneRef"
    ></BindPhone>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import I18nSelect from './I18nSelect.vue'
import LoginDropdown from './LoginDropdown.vue'
import BindPhone from './BindPhone.vue'
import { CommonModule } from '@/store/modules/common'
import { LoginModule } from '@/store/modules/login/index'
import { deepClone } from '@/utils/common'
import router from '@/router/handleRoute'
import { PermissionModule } from '@/store/modules/permission'
interface LoginFrom {
  loginName: string
  password: string
  remember: boolean
  policy: boolean
  loginStatus: boolean
  loginType: string
}
@Component({ name: 'Login', components: { I18nSelect, LoginDropdown, BindPhone } })
export default class Login extends Vue {
  private $router: any
  private $message: any
  private $store: any
  private currentYear: number = 2020
  private loginLoading: boolean = false
  private form: LoginFrom = {
    loginName: '',
    password: '',
    remember: true,
    policy: false,
    loginStatus: true,
    loginType: 'WEBRTC'
  }

  private webchatStatus = true

  private rules: object = {
    loginName: [{ required: true, message: '请输入账号', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
  }

  private changeLoginStatus (status: boolean) {
    this.form.loginStatus = status
  }

  private changeLoginType (type: string) {
    this.form.loginType = type
  }

  private changeWebchatLoginStatus (type: boolean) {
    this.webchatStatus = type
  }

  get getPlatformConfig () {
    const initConfig = this.$store.state.common.initConfig
    const platformConfig = initConfig ? initConfig.platformConfig : {}
    return platformConfig
  }

  private loginSubmit () {
    if (this.loginLoading) {
      return false
    }
    (this as any).$refs.loginForm.validate((valid) => {
      if (valid) {
        const platformConfig = this.getPlatformConfig
        if (!this.form.policy && platformConfig && platformConfig.m7ServiceTerms && platformConfig.m7PrivacyPolicy) { // 没勾选协议 && 不是oem && 不是私云 && 有配置协议url
          this.$message.error('请阅读并同意《服务协议》和《隐私政策》')
          return
        }
        const value = window.localStorage.getItem('loginForm')
        let temp = { loginName: '', password: '', remember: true, policy: false, loginStatus: true, loginType: 'WEBRTC' }
        if (value && value !== 'undefined' && value !== 'null') {
          temp = JSON.parse(value)
        }
        let encrypted = ''
        if (this.form.password === temp.password) { // 取的缓存密码
          encrypted = this.form.password
        }
        const loginData = {
          form: deepClone(this.form),
          encrypted,
          isLogin: true,
          isConnectSocket: true,
          isConnectWebRtc: true,
          webchatStatus: { status: this.webchatStatus ? 'open' : 'close', _id: '' },
          domain: window.location.href.split('/')[2]
        }
        this.loginEvent(loginData)
      } else {
        console.log('error submit!!')
        return false
      }
    })
  }

  private loginEvent (loginData) {
    this.loginLoading = true
    LoginModule.SignIn(deepClone(loginData)).then((loginRes: any) => {
      if (loginRes && loginRes.success) {
        if (loginRes.data.isRefresh) {
          const jsonData = JSON.stringify(loginData)
          localStorage.setItem('jsonData', jsonData)
          localStorage.setItem('newVersion', 'yes')
          localStorage.setItem('refresh', 'yes')
          location.reload()
        } else {
          localStorage.setItem('refresh', 'no')
        }
        const commonAppIdList = ['knowledge_mgt', 'call_task', 'robot', 'sms']
        const publicCache = this.$store.state.common.publicCache || null
        const list = (publicCache && publicCache.commonAppIdList.map(item => item.id)) || [] // 常用应用列表
        const roleList = [...loginRes.data.user.limits]
        PermissionModule.GenerateRoutes(roleList)
        // 设置动态路由
        router.addRoutes(PermissionModule.routes)
        commonAppIdList.forEach(item => {
          if (item === 'call_task' && roleList.includes('call_task')) { // 有预览外呼的权限
            if (!(list.includes('my_call_task_list') || list.includes('my_auto_call_task_list') || list.includes('auto_call_task_list') || list.includes('preview_dialout_list'))) {
              // 我的预览外呼 || 我的自动外呼 || 预览外呼管理 || 自动外呼管理  都没有设置为常用，要把一级菜单的预览外呼剔除
              PermissionModule.delRoutes('call_task')
              CommonModule.updateLoginMenuList({ menu: 'call_task', type: 'delete' })
            }
          } else if (!(roleList.includes(item) && list.includes(item))) {
            if (roleList.includes(item)) {
              PermissionModule.delRoutes(item)
            }
          }
        })
        this.$router.push({ path: (publicCache && publicCache.loginMenuList[0]) || 'home/index' }) // 登录之后，push当前有权限的一级菜单第一个
      } else if (loginRes.code === '2013') { // 手机模式登录，没有手机号要绑定手机号
        (this as any).$refs.bindPhoneRef.open(loginRes.sessionId)
      }
      this.loginLoading = false
    }).catch(() => {
      this.loginLoading = false
    })
  }

  private bindPhoneSuccess () { // 绑定手机号成功
    this.loginSubmit()
  }

  private getLocalFrom () {
    const value = window.localStorage.getItem('loginForm')
    let localForm = this.form
    if (value && value !== 'undefined' && value !== 'null') {
      localForm = JSON.parse(value)
    }
    return localForm
  }

  private showDropdown () {
    (this as any).$refs.loginDropdownRef.open()
  }

  private beforeMount () {
    window.sessionStorage.clear() // 每次到登录页，清除session的缓存
    this.currentYear = new Date().getFullYear()
    this.form = this.getLocalFrom()
  }

  private mounted () {
    const newVersion = localStorage.getItem('newVersion')
    if (newVersion === 'yes') {
      const loginData = JSON.parse(localStorage.getItem('jsonData') as string)
      localStorage.removeItem('newVersion')
      localStorage.removeItem('jsonData')
      this.loginEvent(loginData)
    }
  }
}
</script>
<style lang="stylus" scoped>
.login-view
  width 100%
  height 100%
  .login-left
    width 45%
    background url('../../assets/img/login-bg.png') no-repeat
    height 100%
    background-size cover
    position relative
    .login-logo
      width 150px
      height 38px
      text-align center
      position relative
      z-index 10
      color $fc-gray
      font-weight bold
      font-size 12px
      margin 8px 0 16px
      background url('../../assets/img/logo.png') no-repeat 20px center
      background-size 20px
      .circle
        margin 4px 3px
        display inline-block
        width 3px
        height 3px
        background $fc-gray
        border-radius 5px
      .logo-title
        line-height 38px
  .login-right
    width 55%
    height 100%
    position relative
    .lang-select
      position absolute
      top 12px
      right 16px
      width 90px
    .login-box
      position absolute
      top 45%
      left 50%
      width 300px
      height 280px
      margin-left -150px
      margin-top -140px
      .login-title
        font-weight bold
        font-size 20px
      .status-box
        margin-top 22px
        position relative
        .status-config
          font-size 14px
          float right
          cursor pointer
          color $c-main
      .el-form-item
        margin-bottom 0
      .el-input
        width 300px
        height 40px
        margin-top 20px
      .policy-checkbox-wrap >>> .el-checkbox__input.is-checked + .el-checkbox__label
        color $fc-gray2
      .policy-checkbox-wrap >>> .el-checkbox__input + .el-checkbox__label
        font-size 12px
      .policy-checkbox-wrap
        margin-top 10px
        a
          color $c-main
      .submit
        width 300px
        height 34px
        border-radius 3px
        text-align center
        font-size 14px
        line-height 34px
        font-weight bold
        color #fff
        background-color $c-main
        margin-top 20px
        cursor pointer
.login-footer
  color #686E84
  font-size 12px
  position absolute
  width 300px
  left 50%
  margin-left -150px
  bottom 30px
  .footer-circle
    padding 0 4px
  .line
    width 300px
    height 1px
    border-bottom 1px solid #e6e6e6
    margin 18px 0
  .record-number
    white-space nowrap
  .serve-number
    margin-bottom 18px
</style>
<style lang="stylus">
.login-view
  .lang-select
    .el-input__inner
      border none
      padding 0
      font-size 12px
  .el-checkbox__label
    font-size 14px
  .el-form
    .el-input__inner
      height 40px
      line-height 40px
      font-size 14px
</style>
